package com.tsj.model.utils;

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;

/**
 * AES加密
 * @author taoshujian
 * @version 1.0
 * @since 2025-11-25 16:43:59
 */
public class AesEncrypt {

    private static final String AESTYPE = "AES/ECB/PKCS5Padding";

    /**
     * 加密
     *
     * @param salt 盐
     * @param content 待加密的内容
     * @return
     */
    public static String encrypt(String salt, String content) {
        byte[] encrypt = null;
        try {
            Key key = generateKey(salt);
            Cipher cipher = Cipher.getInstance(AESTYPE);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            encrypt = cipher.doFinal(content.getBytes());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new String(Base64.encodeBase64(encrypt));
    }

    /**
     * 解密
     *
     * @param salt 盐
     * @param encryptData 待解密的密⽂
     * @return
     */
    public static String decrypt(String salt, String encryptData) {
        encryptData = encryptData.replace(" ", "+");
        byte[] decrypt = null;
        try {
            Key key = generateKey(salt);
            Cipher cipher = Cipher.getInstance(AESTYPE);
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] base64Data = encryptData.getBytes();
            decrypt = cipher.doFinal(Base64.decodeBase64(base64Data));
        } catch (Exception e) {
            System.out.println(e.getMessage());
            return "密码错误";
        }
        return new String(decrypt).trim();
    }

    /**
     * 使用标准的PBKDF2算法来生成符合要求的AES密钥，这样既解决了密钥长度问题，又提高了安全性。
     * @param salt
     * @return
     * @throws Exception
     */
    public static Key generateKey(String salt) throws NoSuchAlgorithmException, InvalidKeySpecException {
        if(salt.length() == 16){
            return new SecretKeySpec(salt.getBytes(), "AES");
        }
        SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
        KeySpec spec = new PBEKeySpec(salt.toCharArray(), salt.getBytes(), 65536, 256); // 256位密钥
        SecretKey secret = factory.generateSecret(spec);
        return new SecretKeySpec(secret.getEncoded(), "AES");
    }
}
